package org.example.user.flight;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.example.LoginPage.currentUserId;
import static org.example.LoginPage.currentUserName;


/**
 * 购票, 在air_order表里添加
 */
public class buyAirTicket extends JFrame {
    private JTextField userIdField, flightIdField, passengerNameField, passengerIdCardNumField, contactField, statusField;
    private JButton addButton;
    //创建一个对象获取当前时间
    Date currentDate = new Date();
    // 创建一个日期格式化对象，指定输出时间的格式
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 使用日期格式化对象将日期对象格式化为字符串
    String orderTime = dateFormat.format(currentDate);


    public buyAirTicket() {
        setTitle("用户端机票购买页面");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(8, 2));

        JLabel flightIdLabel = new JLabel("航班id");
        flightIdField = new JTextField();

        JLabel passengerNameLabel = new JLabel("乘客名");
        passengerNameField = new JTextField();

        JLabel passengerIdCardNumLabel = new JLabel("乘客身份证号码");
        passengerIdCardNumField = new JPasswordField();

        JLabel contactLabel = new JLabel("联系方式");
        contactField = new JTextField();


        JLabel statusLabel = new JLabel("订单状态");
        statusField = new JTextField();

        addButton = new JButton("添加");


        // 添加组件到窗口
        add(flightIdLabel);
        add(flightIdField);

        add(passengerNameLabel);
        add(passengerNameField);

        add(passengerIdCardNumLabel);
        add(passengerIdCardNumField);

        add(contactLabel);
        add(contactField);


        add(statusLabel);
        add(statusField);

        add(new JLabel()); // 占位
        add(addButton);

        // 添加添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addUserInfoToDatabase();
            }
        });
    }

    private void addUserInfoToDatabase() {
        int flightId = Integer.parseInt(flightIdField.getText());
        String passengerName = passengerNameField.getText();
        String passengerIdCardNum = passengerIdCardNumField.getText();
        String contact = contactField.getText();
        String status = statusField.getText();


        try {
            // 连接数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:Mysql://localhost:3306/airlines", "root", "123456");

            // 创建插入语句
            String insertQuery = "INSERT INTO air_order (user_id, flight_id, passenger_name, passenger_id_card_num,contact,order_time,status) VALUES(+" +
                    "'" +
                    currentUserId +
                    "'" +
                    " ,?,?,?,?," +
                    "'" +
                    orderTime +
                    "'" +
                    ",?)";

            PreparedStatement statement = conn.prepareStatement(insertQuery);
            statement.setInt(1, flightId);
            statement.setString(2, passengerName);
            statement.setString(3, passengerIdCardNum);
            statement.setString(4, contact);
            statement.setString(5, status);

            /**
             * 可购座位实行-1的操作
             */
            String reduceOne= "UPDATE air_flight SET available_seat=available_seat-1 WHERE flight_id= "+""+flightId+"";
            PreparedStatement statement2 = conn.prepareStatement(reduceOne);
            statement2.executeUpdate(reduceOne);

            // 执行插入操作
            statement.executeUpdate();

            // 关闭连接和语句
            statement.close();
            statement2.close();
            conn.close();

            // 提示添加成功
            JOptionPane.showMessageDialog(this, "添加成功");

            // 清空输入框
            clearFields();

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加失败：" + e.getMessage());
        }
    }

//    /**
//     * 测试-1操作
//     */
//    private void testForReduce() {
//        flightId = Integer.parseInt(flightIdField.getText());
//
//        try {
//            // 连接数据库
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            Connection conn = DriverManager.getConnection("jdbc:Mysql://localhost:3306/airlines", "root", "123456");
//
//            // 创建插入语句
//            String insertQuery = "UPDATE air_flight SET available_seat=available_seat-1 WHERE flight_id= " + flightId;
//            PreparedStatement statement = conn.prepareStatement(insertQuery);
//
//            statement.setInt(1, flightId);
//            // 执行插入操作
//            statement.executeUpdate();
//
//            // 关闭连接和语句
//            statement.close();
//            conn.close();
//
//            // 提示添加成功
//            JOptionPane.showMessageDialog(this, "添加成功");
//
//            // 清空输入框
//            clearFields();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            JOptionPane.showMessageDialog(this, "添加失败：" + e.getMessage());
//        }
//    }

    private void clearFields() {
        flightIdField.setText("");
        passengerNameField.setText("");
        passengerIdCardNumField.setText("");
        contactField.setText("");
        statusField.setText("");
    }

//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            buyAirTicket  buyAirTicketForm = new buyAirTicket();
//            buyAirTicketForm.setSize(300, 200);
//            buyAirTicketForm.setVisible(true);
//        });
//    }
}